package com.star.spring.ratelimit.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步配置类
 * 
 * @author star
 * @since 2025-01-24
 */
@Configuration
@EnableAsync
public class AsyncConfig {

    @Autowired
    private AsyncLogProperties asyncLogProperties;

    /**
     * 日志记录专用线程池
     */
    @Bean("logExecutor")
    public Executor logExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数
        executor.setCorePoolSize(asyncLogProperties.getCorePoolSize());
        
        // 最大线程数
        executor.setMaxPoolSize(asyncLogProperties.getMaxPoolSize());
        
        // 队列容量
        executor.setQueueCapacity(asyncLogProperties.getQueueCapacity());
        
        // 线程名前缀
        executor.setThreadNamePrefix(asyncLogProperties.getThreadNamePrefix());
        
        // 线程空闲时间（秒）
        executor.setKeepAliveSeconds(asyncLogProperties.getKeepAliveSeconds());
        
        // 拒绝策略：由调用线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(asyncLogProperties.isWaitForTasksToCompleteOnShutdown());
        
        // 等待时间
        executor.setAwaitTerminationSeconds(asyncLogProperties.getAwaitTerminationSeconds());
        
        executor.initialize();
        return executor;
    }
}
